package com.woniuxy.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

@Component
public class OSSClientUtil {

    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com
    private String endpoint = "oss-cn-chengdu.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private String accessKeyId = "LTAI5tRTdzhMSgrmrJcUWj9n";
    private String accessKeySecret = "vxxZw4KNZG43mhFnKA1ldcJssKmHPW";


    public String uploadFile(String bucketName, String key, InputStream input) {
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, key, input);
        } catch (OSSException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return "https://" + bucketName + "." + endpoint + File.separator + key;
    }

    public void deleteFile(String bucketName, String key, InputStream input) {
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            if (!ossClient.doesBucketExist(bucketName)) {
                System.out.println("=>bucket不存在");
                return;
            } else {
                System.out.println("=>开始删除");
                ossClient.deleteObject(bucketName, key);
                System.out.println("===========>删除成功");
            }
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }
}
